package com.huike.springboot1.demos.controller;

import com.huike.springboot1.demos.Mapper.RoleMapper;
import com.huike.springboot1.demos.Mapper.User1Mapper;
import com.huike.springboot1.demos.pojo.Role;
import com.huike.springboot1.demos.pojo.User1;
import com.huike.springboot1.demos.service.User1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/roles")
public class UserController {

    @Autowired
    User1Mapper user1Mapper;
    @Autowired
    private User1Service user1Service;
    @Autowired
    private RoleMapper roleMapper;

    // 用户列表页（需user:view权限）
    @GetMapping
//    @PreAuthorize("hasAuthority('user:view')")
    public String list(Model model, @AuthenticationPrincipal User user) {
        List<User1> users = user1Mapper.user1Select();
        model.addAttribute("currentUser", user.getUsername());//获取当前用户名
        model.addAttribute("users", users);
        return "admin/user/list";
    }

    // 跳转新增页（需user:add权限）
    @GetMapping("/add")
//    @PreAuthorize("hasAuthority('user:add')")
    public String toAdd(Model model, @AuthenticationPrincipal User user) {
        model.addAttribute("user", new User1()); // 空用户对象
        model.addAttribute("allRoles", roleMapper.selectAll()); // 所有角色
        model.addAttribute("currentUser", user.getUsername());//获取当前用户名
        return "admin/user/form";
    }

    // 跳转编辑页（需user:edit权限）
    @GetMapping("/edit/{id}")
//    @PreAuthorize("hasAuthority('user:edit')")
    public String toEdit(@PathVariable Long id, Model model, @AuthenticationPrincipal User user) {
        User1 user1 = user1Service.findById(id);
        // 获取用户已关联的角色ID
        User1 userWithRoles = user1Service.findUserWithRoles(id);
        List<Long> userRoleIds = userWithRoles.getRoles().stream()
                .map(Role::getId)
                .collect(Collectors.toList());
        model.addAttribute("currentUser", user.getUsername());//获取当前用户名
        model.addAttribute("user", user1);
        model.addAttribute("allRoles", roleMapper.selectAll()); // 所有角色
        model.addAttribute("userRoleIds", userRoleIds); // 用户已选角色ID
        return "admin/user/form";
    }

    // 保存用户（新增/编辑）
    @PostMapping("/save")
//    @PreAuthorize("hasAnyAuthority('user:add', 'user:edit')")
    public String save(
            User1 user1,
            @RequestParam(required = false, name = "roleIds") List<Long> roleIds, // 角色ID列表
            RedirectAttributes redirect
    ) {
        // 1. 新增才需要验重；编辑时用户名本身不改
        if (user1.getId() == null) {
            int cnt = user1Mapper.countByUsername(user1.getUsername());
            if (cnt > 0) {
                redirect.addFlashAttribute("error", "用户名已存在，请更换！");
                return "redirect:/roles";   // 回到新增页
            }
            if (user1Service.existsByEmail(user1.getEmail())) {
                redirect.addFlashAttribute("error", "邮箱已注册，请直接登录或更换邮箱！");
                return "redirect:/roles";   // 回到用户列表页
            }
        }
        try {
            if (user1.getId() == null) {
                // 新增
                user1.setPassword("123456");//设置默认密码为123456
                user1Service.add(user1, roleIds);
                redirect.addFlashAttribute("msg", "新增用户成功");
            } else {
                // 编辑
                user1Service.update(user1, roleIds);
                redirect.addFlashAttribute("msg", "更新用户成功");
            }
        } catch (Exception e) {
            redirect.addFlashAttribute("error", "操作失败：" + e.getMessage());
            return "redirect:/roles";
        }
        return "redirect:/roles";
//        转发只有一次请求，转发可以是内部的转发，
//        重定向是有两次请求，第一个请求会给出另一个路径进行二次请求，重定向可以是外部的，也可以内部，
//        重定向第一次网络请求的状态码是302(http状态码)，302表示跳转
    }

    // 删除用户（需user:delete权限）
    @GetMapping("/delete/{id}")
//    @PreAuthorize("hasAuthority('user:delete')")
    public String delete(@PathVariable Long id, RedirectAttributes redirect) {
        try {
            user1Service.delete(id);
            redirect.addFlashAttribute("msg", "删除用户成功");
        } catch (Exception e) {
            redirect.addFlashAttribute("error", "删除失败：" + e.getMessage());
        }
        return "redirect:/roles";
    }
}